package com.shop.front.shiro;

import com.alibaba.fastjson.JSON;
import com.shop.web.response.BaseResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录身份过滤器
 */
public class UserLoginFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        return subject.getPrincipal() != null;
    }

    /**
     * 未获取到登录身份，返回错误码
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setContentType("application/json;charset=UTF-8");
        httpResponse.getWriter().write(JSON.toJSONString(BaseResponse.NEED_LOGIN));
        return false;
    }
}
